package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired  //购物车
    private ShoppingCartService shoppingCartService;
    @Autowired  //订单
    private OrderDetailService orderDetailService;
    @Autowired  //地址簿
    private AddressBookService addressBookService;
    @Autowired  //用户
    private UserService userService;

    /**
     * 下单方法
     *
     * @param orders
     */

    @Override
    public void submit(Orders orders) {
        //先获取用户id
        Long currentId = BaseContext.getCurrentId();
        //获取用户信息
        User user = userService.getById(currentId);

        //获取地址簿的信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, currentId);
        //获取购物车信息
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        //生成订单号
        long id = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCartItem : list) {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCartItem.getNumber()); //数量
            orderDetail.setDishFlavor(shoppingCartItem.getDishFlavor()); //口味
            orderDetail.setDishId(shoppingCartItem.getDishId()); //菜品id
            orderDetail.setSetmealId(shoppingCartItem.getSetmealId());//套餐id
            orderDetail.setName(shoppingCartItem.getName()); //名称
            orderDetail.setImage(shoppingCartItem.getImage()); //图片
            orderDetail.setAmount(shoppingCartItem.getAmount());//金额（单价）
            amount.addAndGet(shoppingCartItem.getAmount().multiply(new BigDecimal(shoppingCartItem.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        //组装订单数据
        //订单号
        orders.setId(id);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //订单状态
        orders.setStatus(2);
        //实收金额
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        //用户id
        orders.setUserId(currentId);
        //
        orders.setNumber(String.valueOf(id));
        //登陆用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //手机号
        orders.setPhone(addressBook.getPhone());
        //地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //2. 保存到订单表
        save(orders);
        //3 保存到订单明细表
        orderDetailService.saveBatch(orderDetails);
        //4. 清空购物车
        shoppingCartService.remove(lqw);
    }

    /**
     * 再来一单
     *
     * @param orders
     */
    @Override
    public void again(Orders orders) {
        //获取订单信息
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> detailList = orderDetailService.list(lqw);

        //拷贝赋值
        List<ShoppingCart> list = detailList.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(list);
    }
}